import tkinter as tk
from tkinter import ttk, messagebox
from gui.notification_config_gui import NotificationConfigFrame
from gui.monitor_page import MatchViewer
from config_loader import load_global_config, get_full_config_path


class MainApplication:
    """
    主应用程序类
    """

    def __init__(self, root):
        # 加载全局配置
        load_global_config(get_full_config_path())

        self.root = root
        self.root.title("球探数据监测")
        self.root.geometry("1000x700")

        # 创建菜单栏
        self.create_menu()

        # 直接使用root作为MatchViewer的父窗口
        self.match_viewer = MatchViewer(self.root)

    def create_menu(self):
        """
        创建菜单栏
        """
        # 创建菜单栏
        menubar = tk.Menu(self.root)
        self.root.config(menu=menubar)

        # 创建设置菜单
        settings_menu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="设置", menu=settings_menu)
        
        # 添加通知设置选项
        settings_menu.add_command(label="通知设置", command=self.open_notification_config)

    def open_notification_config(self):
        """
        打开通知配置窗口
        """
        # 创建一个新的顶级窗口
        notification_config_window = tk.Toplevel(self.root)
        notification_config_window.title("通知设置")
        notification_config_window.geometry("600x700")
        notification_config_window.transient(self.root)  # 设置为父窗口的临时窗口
        notification_config_window.grab_set()  # 模态窗口

        # 创建通知配置框架
        notification_frame = NotificationConfigFrame(notification_config_window, config_file_path=get_full_config_path())
        notification_frame.pack(fill=tk.BOTH, expand=True)

        # 居中显示窗口
        self.center_window(notification_config_window)

    def center_window(self, window):
        """
        将窗口居中显示
        """
        window.update_idletasks()
        width = window.winfo_width()
        height = window.winfo_height()
        x = (window.winfo_screenwidth() // 2) - (width // 2)
        y = (window.winfo_screenheight() // 2) - (height // 2)
        window.geometry(f"{width}x{height}+{x}+{y}")


def main():
    """
    主函数
    """
    root = tk.Tk()
    app = MainApplication(root)
    
    # 设置窗口关闭事件
    def on_closing():
        if hasattr(app, 'match_viewer') and hasattr(app.match_viewer, 'log_running'):
            app.match_viewer.log_running = False
            if hasattr(app.match_viewer, 'odds_monitor'):
                app.match_viewer.odds_monitor.stop_monitoring()
        root.destroy()

    root.protocol("WM_DELETE_WINDOW", on_closing)
    root.mainloop()


if __name__ == "__main__":
    main()